function updateStyle1() {
  document.getElementById("msg").style.opacity = 1;
}

function updateStyle0() {
  document.getElementById("msg").style.opacity = 0;
}

function getData() {
  const Email = document.getElementById("Email").value;
  const PassWord = document.getElementById("PassWord").value;
  const Copy = document.getElementById("Copy").value;
  console.log(Email, PassWord, Copy);

  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailReg.test(Email)) {
    document.getElementById("msg").innerText = "邮箱格式不正确";
    updateStyle1();
    return;
  }

  if (PassWord !== Copy) {
    document.getElementById("msg").innerText = "两次密码不一致";
    document.getElementById("msg").style.color = "#f00";
    updateStyle1();
    return;
  }

  document.getElementById("msg").innerText = "";
  updateStyle0();
}

function sendVerificationCode() {
  const email = document.getElementById("Email").value;
  if (!email) {
    document.getElementById("msg").innerText = "请输入邮箱";
    updateStyle1();
    return;
  }

  fetch("/sendCode", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email }),
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.success) {
        document.getElementById("msg").innerText = "验证码已发送到您的邮箱";
      } else {
        document.getElementById("msg").innerText = "发送验证码失败，请重试";
      }
      updateStyle1();
    })
    .catch((error) => {
      console.error("Error:", error);
      document.getElementById("msg").innerText = "发送请求出错";
      updateStyle1();
    });
}

function Register() {
  const data = {
    userName: document.getElementById("UserName").value,
    email: document.getElementById("Email").value,
    password: document.getElementById("PassWord").value,
    code: document.getElementById("Code").value,
  };
  if (data.userName == "" || data.email == "" || data.password == "" || data.code == "") {
    alert("请填写完整信息");
  } else {
    fetch("/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })
      .then((response) => response.json())
      .then((data) => {
        if (data.success) {
          alert(data.message);
          document.getElementById("msg").innerText = "";
          updateStyle0();
        } else {
          document.getElementById("msg").innerText = data.message;
          updateStyle1();
        }
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("注册失败，请稍后再试");
      });
  }
}
